package com.example.biji;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.LayoutInflaterCompat;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    Context context = this;
    private NoteDatabase dbHelper;
    private NoteAdapter adapter;
    private List<Note> noteList = new ArrayList<>();

    private static final String TAG = "MainActivity";

    private ActivityResultLauncher launcher;
    FloatingActionButton btn;
    private ListView lv;

    private Toolbar myToolbar;

    //弹出菜单
    private PopupWindow popupWindow;
    private PopupWindow popupCover;
    private View customView;
    private View coverView;
    private WindowManager wm;
    private DisplayMetrics metrics;
    private LayoutInflater layoutInflater;
    private RelativeLayout main;
    private TextView setting_text;
    private ImageView setting_image;
    private ListView lv_tag;
    private TextView add_tag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initActivityResult();
        btn = findViewById(R.id.fab);


        lv = findViewById(R.id.lv);


        adapter = new NoteAdapter(context, noteList);
        refreshListView();
        lv.setAdapter(adapter);
        myToolbar = findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//设置toolbar取代actionBar
        initPopUpView();

        myToolbar.setNavigationIcon(getDrawable(R.drawable.ic_menu_black_24dp));

        myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopUpView();
            }
        });
        lv.setOnItemClickListener(this);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, EditActivity.class);
                intent.putExtra("mode", 4);//新建笔记的值为4
                launcher.launch(intent);
            }
        });


    }

    @Override
    protected void needRefresh() {
//        setNightMode();
//        startActivity(new Intent(this, MainActivity.class));
//        finish();
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    }

    public void initPopUpView() {
        layoutInflater = (LayoutInflater)
                MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        customView = layoutInflater.inflate(R.layout.setting_layout, null);
        coverView = layoutInflater.inflate(R.layout.setting_cover, null);

        main = findViewById(R.id.main_layout);
        wm = getWindowManager();
        metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }
        if (popupCover != null && popupCover.isShowing()) {
            popupCover.dismiss();
            popupCover = null;
        }
    }

    public void showPopUpView() {
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        popupCover = new PopupWindow(coverView, width, height, false);
        popupWindow = new PopupWindow(customView, (int) (width * 0.7), height, true);

        if (isNightMode()) popupWindow.setBackgroundDrawable(new ColorDrawable(Color.LTGRAY));
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));

//    popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        //在主界面加载成功之后 显示弹出
        findViewById(R.id.main_layout).post(new Runnable() {
            @Override
            public void run() {
                popupCover.showAtLocation(main, Gravity.NO_GRAVITY, 0, 0);
                popupWindow.showAtLocation(main, Gravity.NO_GRAVITY, 0, 0);
                setting_text = customView.findViewById(R.id.setting_settings_text);
                setting_image = customView.findViewById(R.id.setting_settings_image);
                lv_tag = customView.findViewById(R.id.lv_tag);
                add_tag = customView.findViewById(R.id.add_tag);
                setting_text.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, UserSettingsActivity.class));
                        overridePendingTransition(R.anim.in_lefttoright, R.anim.no);

                    }
                });
                setting_image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, UserSettingsActivity.class));
                        overridePendingTransition(R.anim.in_lefttoright, R.anim.no);

                    }
                });

                coverView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        popupWindow.dismiss();
                        return false;
                    }
                });

                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        popupCover.dismiss();
                    }
                });
            }
        });

        View settingsBtn = customView.findViewById(R.id.settings);
        settingsBtn.setOnClickListener(v -> {
            Intent intent = new Intent(this, UserSettingsActivity.class);
            startActivity(intent);
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);

        MenuItem mSearch = menu.findItem(R.id.action_search);
        SearchView mSearchView = (SearchView) mSearch.getActionView();
        mSearchView.setQueryHint("搜索");
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Toast.makeText(context, "search", Toast.LENGTH_SHORT).show();
                adapter.getFilter().filter(newText);
                return false;
            }
        });


        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.delete_all) {
            new AlertDialog.Builder(MainActivity.this).setMessage("要删除全部吗?").setPositiveButton(android.R.string.yes,

                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dbHelper = new NoteDatabase(context);
                            SQLiteDatabase db = dbHelper.getWritableDatabase();
                            db.delete("notes", null, null);
                            db.execSQL("update sqlite_sequence set seq=0 where name='notes'");
                            refreshListView();
                        }
                    }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).create().show();
        }
        return super.onOptionsItemSelected(item);
    }


    private void refreshListView() {
        CRUD op = new CRUD(context);
        op.open();
        if (noteList.size() > 0) {
            noteList.clear();
        }
        noteList.addAll(op.getAllNotes());
        op.close();
        adapter.notifyDataSetChanged();
    }


    public void initActivityResult() {
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {


                        int returnMode = result.getData().getIntExtra("mode", -1);
                        long note_id = result.getData().getLongExtra("id", 0);
                        if (returnMode == 1 && result.getResultCode() == RESULT_OK) {//更新笔记
                            String content = result.getData().getStringExtra("content");
                            String time = result.getData().getStringExtra("time");
                            int tag = result.getData().getIntExtra("tag", 1);
                            Note note = new Note(content, time, tag);
                            note.setId(note_id);
                            CRUD op = new CRUD(context);
                            op.open();
                            op.updateNote(note);
                            op.close();

                        } else if (returnMode == 0 && result.getResultCode() == RESULT_OK) {//创建新笔记
                            String content = result.getData().getStringExtra("content");
                            String time = result.getData().getStringExtra("time");
                            int tag = result.getData().getIntExtra("tag", 1);
                            Note note = new Note(content, time, tag);
                            CRUD op = new CRUD(context);
                            op.open();
                            op.addNote(note);
                            op.close();


                        } else if (returnMode == 2 && result.getResultCode() == RESULT_OK) {//删除笔记

                            Note note = new Note();
                            note.setId(note_id);
                            CRUD op = new CRUD(context);
                            op.open();
                            op.removeNote(note);
                            op.close();


                        }

                        refreshListView();

                    }
                });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Note curNote = (Note) parent.getItemAtPosition(position);
        Intent intent = new Intent(MainActivity.this, EditActivity.class);
        intent.putExtra("content", curNote.getContent());
        intent.putExtra("id", curNote.getId());
        intent.putExtra("time", curNote.getTime());
        intent.putExtra("mode", 3);
        intent.putExtra("tag", curNote.getTag());
        launcher.launch(intent);
    }


}